package com.unlp.distribuida.controller;

import java.util.List;

import org.apache.log4j.Logger;
import org.rrest.core.filesystem.FileSystemManager;
import org.rrest.file.FileInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RmiRestController {

	private static final Logger LOGGER = Logger
			.getLogger(RmiRestController.class);

	@Autowired
	private FileSystemManager fileSystem;

	@ResponseBody
	@RequestMapping(value = "/rest/random", method = RequestMethod.GET)
	public ResponseEntity<FileInfo> getRandomFile() {
		LOGGER.info("Calling getRandomFile");
		return new ResponseEntity<FileInfo>(FileInfo.randomFile(1024),
				HttpStatus.OK);
	}

	@ResponseBody
	@RequestMapping(value = "/rest/get/{path:.*}", method = RequestMethod.GET)
	public ResponseEntity<FileInfo> getFile(@PathVariable String path) {
		LOGGER.info("Calling getFile");
		HttpStatus status = HttpStatus.OK;
		FileInfo res = this.fileSystem.getFile(path);
		if (res == null) {
			status = HttpStatus.INTERNAL_SERVER_ERROR;
		}
		return new ResponseEntity<FileInfo>(res, status);

	}

	@ResponseBody
	@RequestMapping(value = "/rest/add", method = RequestMethod.POST)
	public ResponseEntity<String> addFile(@RequestBody FileInfo fileInfo) {
		LOGGER.info("Calling addFile");
		HttpStatus status = HttpStatus.OK;
		if (!this.fileSystem.addFile(fileInfo)) {
			status = HttpStatus.INTERNAL_SERVER_ERROR;
		}
		return new ResponseEntity<String>(status);

	}

	@ResponseBody
	@RequestMapping(value = "/rest/remove/{path:.*}", method = RequestMethod.GET)
	public ResponseEntity<String> deleteFile(@PathVariable String path) {
		LOGGER.info("Calling deleteFile");
		HttpStatus status = HttpStatus.OK;
		if (!this.fileSystem.deleteFile(path)) {
			status = HttpStatus.INTERNAL_SERVER_ERROR;
		}
		return new ResponseEntity<String>(status);
	}

	@ResponseBody
	@RequestMapping(value = "/rest/list/{path}", method = RequestMethod.GET)
	public ResponseEntity<List<String>> list(@PathVariable String path) {
		LOGGER.info("Calling listFiles");
		if (path == null) {
			path = "/";
		}
		return new ResponseEntity<List<String>>(
				this.fileSystem.listFiles(path), HttpStatus.OK);
	}

	@ResponseBody
	@RequestMapping(value = "/rest/list/", method = RequestMethod.GET)
	public ResponseEntity<List<String>> listRoot() {
		return this.list(null);
	}

}
